//
//  FMDBUtils.m
//  oc1
//
//  Created by kokuma on 2017/2/20.
//  Copyright © 2017年 kokumams. All rights reserved.
//??@"/tmp/tmp.db"; 这个路径直接用？？
//[NSNull null]

#import "FMDBUtils.h"
static NSString *const dbPath=@"tmp.db";
static NSString *const tableEdit=@"edit";

@implementation FMDBUtils

+ (FMDBUtils *)sharedFMDB {
    static FMDBUtils *shared_manager = nil;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        shared_manager = [[self alloc] init];
    });
    return shared_manager;
}

- (void)deleteDB{
    // Delete the old database
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:dbPath error:NULL];
}

- (BOOL)openOrCreateDB{
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:dbPath];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
        // [db release];
        _db = nil;
        return NO;
    }
    return YES;
}

-(BOOL)createTableEdit{
    BOOL success = [self openOrCreateDB];
    if(!success){
        NSLog(@"openOrCreateDB-error");
        return NO;
    }
   BOOL isExisted = [_db tableExists:tableEdit];
    if(isExisted){
        return YES;
    }else{
        NSString *sql = @"create table edit (id integer primary key autoincrement, title text, content text);";
        //"create table login (id integer primary key autoincrement, mobile text, loginPwd text);";
        
        BOOL success = [_db executeStatements:sql];
        NSLog(@"createTables");
        return success;
    }
}


-(NSMutableArray *)queryEditData{
     NSLog(@"queryEditData");
    NSMutableArray *queryData= [[NSMutableArray alloc]init];
    if (![_db columnExists:@"title" inTableWithName:tableEdit]){
        NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ TEXT",@"edit",@"title"];
        BOOL worked = [_db executeUpdate:alertStr];
        if(worked){
            NSLog(@"插入成功");
        }else{
            NSLog(@"插入失败");
        }
    }else{
        NSLog(@"有了title字段");
    }
    FMResultSet *s = [_db executeQuery:[NSString stringWithFormat:@"%@%@", @"SELECT * FROM ", tableEdit]];
    while ([s next]) {
        //retrieve values for each record
        NSString *title = [s stringForColumn:@"title"];
        NSString *content = [s stringForColumnIndex:2];
         NSLog(@"results1 = %@", [s stringForColumnIndex:0]);
         NSLog(@"results1 = %@", [s objectForColumnName:@"title"]);
         NSLog(@"results1 = %@", [s stringForColumnIndex:2]);
        NSLog(@"results1 = %@", [s stringForColumnIndex:3]);
        // int id=  [s intForColumn:@"id"];
       NSString * idIndex= [s stringForColumnIndex:0];
        [queryData addObject:idIndex];
        [queryData addObject:title];
        [queryData addObject:content];
      return queryData;
    }
    return Nil;
}

- (BOOL)insertOrUpdateEditData:(NSString *)mytitle mycontent:(NSString *)mycontent {
    NSLog(@"title");
    NSLog(mytitle);
     NSLog(mycontent);
    BOOL success = [self createTableEdit];
    if(!success){
        NSLog(@"Update-error = %@", [_db lastErrorMessage]);
        return success;
    }
    NSMutableArray *queryData =[self queryEditData];
    if(queryData){
        NSString *idIndex=queryData.firstObject;
        if(idIndex){
            BOOL success = [_db executeUpdate:@"UPDATE edit SET title=?,content=? WHERE id=?", mytitle, mycontent,idIndex];
            if (!success) {
                NSLog(@"Update-error = %@", [_db lastErrorMessage]);
                return NO;
            }else{
                NSLog(@"Insert-succ-update");
                return YES;
            }
        }else{
            BOOL success = [_db executeUpdate:@"INSERT INTO edit (title, content) VALUES (?, ?)", mytitle, mycontent];
            if (!success) {
                NSLog(@"Insert-error = %@", [_db lastErrorMessage]);
                return NO;
            }else{
                NSLog(@"Insert-succ-insert");
                return YES;
            }
            
        }
    }
    
    return NO;
}

- (void)closeDb{
    [_db close];
}

@end
